const video = $('#video');
const $play = $('.play');

// 进度条
const progress = $('.progress');
const cache = $('.progress__cache');
const time = $('.progress__time');
var timeCount;
let curTime;
let timeLen = 0;
let cacheLen = 0;
function progressA() {
  timeLen = timeLen + (300 / video[0].duration);
  cacheLen = cacheLen + (300 / video[0].progress)
  time.css("width", `${timeLen}px`);
  cache.css("width", `${cacheLen}px`)
  timeCount = setTimeout(progressA, 1000);
  if (video[0].ended) {
    clearTimeout(timeCount);
  }
}

function countTime(timeType) {
  const hourNum = parseInt(timeType / 3600);
  const hour = hourNum.toString().length <= 1 ? '0' + hourNum : hourNum;

  const minuteNum = parseInt(timeType / 60);
  const minute = minuteNum.toString().length <= 1 ? '0' + minuteNum: minuteNum

  const secNum = Math.ceil(timeType % 60);
  const sec = secNum.toString().length <= 1? '0' + secNum : secNum;

  const totalTime = `${hour}:${minute}:${sec}`;
  return totalTime;
}

// 监听视频载入
video.on('loadedmetadata', () => {
  $('.total__time').text(countTime(video[0].duration));
  video[0].width = 550;

  // 音量
  const $volumeBar = $('.volume__bar');
  const $volumeRound = $('.volume__bar__round');
  $volumeRound.css("left", "100%");
  $volumeBar.on('click', (event) => {
    $this = $(event.currentTarget);

    const left = event.clientX - $this.offset().left
    if ((left / 100) < 0 || (left / 100) > 1 ) return;
    video[0].volume = (left / 100);
    $volumeRound.css("left", `${left - 10}px`);
  });
})

// 监听视频播放
function fetcCurrentTime() {
  $('.current__time').text(countTime(video[0].currentTime));
  setTimeout(fetcCurrentTime, 1000)
}

video.on('play', () => {

  // 点击调整播放进度
  progress.on('click', (event) => {
    $this = $(event.currentTarget);
    timeLen = event.clientX - $this.offset().left
    time.css("width", `${timeLen}px`);
    curTime = (event.clientX - $this.offset().left) / (300 / video[0].duration);
    video[0].currentTime = curTime;
  });
  
  curTime = setTimeout(fetcCurrentTime, 1000);
})

// 监听播放结束
video.on('ended', () => {
  width = 0;
  $play.removeClass('pause').addClass('player');
})

// 暂停播放
$play.on('click', () => {
  if (video[0].paused) {
    video[0].play();
    $play.removeClass('player').addClass('pause');
    setTimeout(progressA, 1000);
  } else {
    video[0].pause();
    clearTimeout(timeCount);
    $play.removeClass('pause').addClass('player');
  }
})
